package service

import (
	"crow-docker/src/config"
	"crow-docker/src/models"
	"errors"
	"github.com/toolkits/pkg/logger"
)

func UpdateUserInfo(updateUserInfoRequire UpdateUserInfoRequest) (err error) {

	tx := config.MyTx
	defer func() {
		if err != nil {
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()
	var sysUsers models.SysUser
	sysUsers.ID = updateUserInfoRequire.Id
	sysUsers.Email = updateUserInfoRequire.Email
	sysUsers.Phone = updateUserInfoRequire.Phone
	logger.Info(sysUsers)

	err = models.UpdateUserInfoByID(sysUsers, tx)
	if err != nil {
		logger.Error(err)
		return err
	}
	return nil
}

func UpdateUserPassword(updateUserPasswordRequire UpdateUserPasswordRequest) (err error) {
	tx := config.MyTx
	defer func() {
		if err != nil {
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()
	//旧密码认证
	passwordMd5 := EncryptWithMd5(updateUserPasswordRequire.Password)
	logger.Info("PasswordMd5 :", passwordMd5)

	result, userId, err := models.CheckUser(updateUserPasswordRequire.UserName, passwordMd5, tx)
	if err != nil {
		logger.Error(err)
		return err
	}
	logger.Infof("%s 用户，ID:%d ,比对结果: %t", updateUserPasswordRequire.UserName, userId, result)

	if result == false {
		err = errors.New("密码错误")
		logger.Error(err)
		return err
	}

	//修改密码
	var sysUsers models.SysUser
	sysUsers.UserName = updateUserPasswordRequire.UserName
	sysUsers.Password = EncryptWithMd5(updateUserPasswordRequire.NewPassword)
	logger.Info(sysUsers)
	err = models.UpdateUserInfoByUserName(sysUsers, tx)
	if result == false {
		logger.Error(err)
		return err
	}
	return nil
}

func GetUserInfo(userName string) (userInfo models.SysUser, err error) {
	tx := config.MyTx
	defer func() {
		if err != nil {
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()
	userInfo, err = models.GetUserByUserName(userName, tx)
	if err != nil {
		return userInfo, err
	}
	logger.Info(userInfo)
	return userInfo, err
}

func Logout(strToken string) error {

	//删除redis中的token
	err := config.Rdb.Del(config.RedisCtx, ShortTokenKeyPrefix+strToken).Err()
	if err != nil {
		logger.Error(err)
		return err
	}
	return nil
}
